package com.li.shop.controller;

import com.li.shop.domain.Product;
import com.li.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

//杨煦瑞做，用于商品搜索操作
@Controller
@RequestMapping("/search")
public class ProductSearchController {
    @Autowired
    private ProductService productService;

    @GetMapping("preSearch")
    public String preSearch(){
        return "before/search";
    }

    @PostMapping("/products")
    public String productSearch(@RequestParam("search") String searchContent, HttpServletRequest request, HttpServletResponse response, Model model){
        HttpSession session=request.getSession();

        List<Product> products = productService.findByProductName(searchContent);
        for (Product product:products) {
            if(product.getProductPic()==null || product.getProductPic()==""){
                product.setProductPic("default");
            }
        }
        model.addAttribute("products",products);
        session.setAttribute("searchContent",searchContent);

        return "before/search";
    }

    //按照价格优先排序，升序排序
    @RequestMapping("/sortBySoldPrice")
    public String sortByPrice(HttpServletRequest request, HttpServletResponse response, Model model){
        HttpSession session=request.getSession();
        String searchContent= (String) session.getAttribute("searchContent");        //从session中拿到数据
        List<Product> products= productService.sortByPrice(searchContent);

        model.addAttribute("products",products);
        return "before/search";
    }

    //按照销量优先排序，升序排序
    @RequestMapping("/sortBySalesVolume")
    public String sortBySalesVolume(HttpServletRequest request, HttpServletResponse response, Model model){
        HttpSession session=request.getSession();
        String searchContent= (String) session.getAttribute("searchContent");        //从session中拿到数据
        List<Product> products= productService.sortBySalesVolume(searchContent);

        model.addAttribute("products",products);
        return "before/search";
    }

}


